package id.net.iconpln.bb.client.view.secman;

import id.net.iconpln.bb.client.service.SecmanService;
import id.net.iconpln.bb.client.service.SecmanServiceAsync;
import id.net.iconpln.bb.client.util.ClientModule;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.core.FastMap;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.layout.FitData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class PageBbMasterUser extends LayoutContainer{
	private final SecmanServiceAsync secmanService = GWT.create(SecmanService.class);
	
	private static final String generateBySystem = "Generated By System.";
	
	ListStore storeGpMasterUser, storeCbUnit;
	ListStore storeCbLevelUser;
	
	private Grid gpMasterUser;
	private TextField tfIdUser, tfNamaUser, tfPassword, tfNoNip, tfAlamat, tfTelp, tfEmail, tfNamaPanjang;
	private ComboBox cbUnit, cbLevelUser;
	private TextField tfPasswordOriginal;

    private Button bSubmit = new Button("Submit");
    private Button bDelete = new Button("Delete");

	Map mapParam;

	@Override
	protected void onRender(Element parent, int index) 
	{
	    super.onRender(parent, index);
	    
	    setLayout(new FitLayout());	    
	    initStore();

	    ContentPanel cp = new ContentPanel();  

	    cp.setHeading("Master User");  
	    cp.setFrame(true);  
	    cp.setSize(900, 400);  
	    cp.setLayout(new RowLayout(Orientation.HORIZONTAL));  
	    
	    gpMasterUser = createGridMasterUser();
	    gpMasterUser.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
	    gpMasterUser.getSelectionModel().addListener(Events.SelectionChange, new Listener<SelectionChangedEvent<ModelData>>() {
			@Override
			public void handleEvent(SelectionChangedEvent<ModelData> be) {
				ModelData md = (ModelData) be.getSelectedItem();
				tfIdUser.setValue(md.get("id_user"));
				tfNamaUser.setValue(md.get("nama_user"));
				tfPassword.setValue(md.get("password"));
				tfNoNip.setValue(md.get("no_nip"));
				tfAlamat.setValue(md.get("alamat"));
				tfTelp.setValue(md.get("telp"));
				tfEmail.setValue(md.get("email"));
				tfNamaPanjang.setValue(md.get("nama_panjang"));
				
				tfPasswordOriginal.setValue(md.get("password").toString());
				
				ModelData dummyUnit = new BaseModelData();
				dummyUnit.set("id_singkat", md.get("unit"));
				dummyUnit.set("nama_unit", md.get("nama_unit"));
				cbUnit.setValue(dummyUnit);

				ModelData dummyLevel = new BaseModelData();
				dummyLevel.set("id_level", md.get("level_user"));
				dummyLevel.set("keterangan", md.get("nama_level"));
				cbLevelUser.setValue(dummyLevel);
				
				bSubmit.enable();
				bDelete.enable();
			}
		});
	    
			
	    FormPanel panel = createFormInput();

	    cp.add(panel, new RowData(.4, 1));
	    cp.add(gpMasterUser, new RowData(.6, 1));
		
	    add(cp, new FitData(5));
	}
	
	// Store
	private void initStore()
	{
		storeGpMasterUser = new ListStore();
		initGridStore();

		Map map = new FastMap();
		//map.put("id_unit", "IP.SUR");
		map.put("id_unit", Registry.get("idPltu"));
		
		storeCbUnit = new ListStore();
		secmanService.getMasterUnit(map, new AsyncCallback<List<Map>>() {
			public void onFailure(Throwable caught) {
				GWT.log(caught.getMessage(), null);
			}

			public void onSuccess(List<Map> result) {	
				storeCbUnit.removeAll();
				storeCbUnit.add(ClientModule.setListBaseModelFromListMap(result));
			}
		});


		storeCbLevelUser = new ListStore();
		secmanService.getMasterLevelUserAll(new AsyncCallback<List<Map>>() {
			public void onFailure(Throwable caught) {
				GWT.log(caught.getMessage(), null);
			}

			public void onSuccess(List<Map> result) {	
				storeCbLevelUser.removeAll();
				storeCbLevelUser.add(ClientModule.setListBaseModelFromListMap(result));
			}
		});
	}
	
	private void initGridStore()
	{
		Map map = new FastMap();
		//map.put("id_unit", "IP.SUR");
		map.put("id_unit", Registry.get("idPltu"));
		
		secmanService.getMasterUser(map, new AsyncCallback<List<Map>>() {
			public void onFailure(Throwable caught) {
				GWT.log(caught.getMessage(), null);
			}

			public void onSuccess(List<Map> result) {	
				storeGpMasterUser.removeAll();
				storeGpMasterUser.add(ClientModule.setListBaseModelFromListMap(result));
			}
		});
	}
	
	// Grid
	private Grid createGridMasterUser()
	{
		List<ColumnConfig> configs = new ArrayList<ColumnConfig>();
		
		ColumnConfig column;

		column = new ColumnConfig("id_user","ID", 30);
		configs.add(column);
		
		column = new ColumnConfig("nama_user","Login", 100);
		configs.add(column);
		
		column = new ColumnConfig("password","Password", 100);
		column.setRenderer(new GridCellRenderer<ModelData>() {
			@Override
			public Object render(ModelData model, String property,
					ColumnData config, int rowIndex, int colIndex,
					ListStore<ModelData> store, Grid<ModelData> grid) {
				return "*********";
			}
		});
		configs.add(column);
		
		column = new ColumnConfig("nama_panjang","Nama", 150);
		configs.add(column);
		
		column = new ColumnConfig("unit","Unit", 100);
		column.setHidden(true);
		configs.add(column);
		column = new ColumnConfig("nama_unit","nama_unit", 200);
		configs.add(column);
		
		column = new ColumnConfig("level_user","Level User", 80);
		column.setHidden(true);
		configs.add(column);
		column = new ColumnConfig("nama_level","nama_level", 150);
		configs.add(column);
		
		column = new ColumnConfig("alamat","Alamat", 200);
		configs.add(column);
		
		column = new ColumnConfig("no_nip","Nip", 100);
		configs.add(column);
		
		column = new ColumnConfig("telp","No Telp", 120);
		configs.add(column);
		
		column = new ColumnConfig("email","Email", 200);
		configs.add(column);
		
		storeGpMasterUser.setMonitorChanges(true);
		ColumnModel cm = new ColumnModel(configs);
		gpMasterUser = new Grid(storeGpMasterUser, cm);
		gpMasterUser.getView().setEmptyText("Data tidak ditemukan");
		gpMasterUser.setBorders(true);
		gpMasterUser.setStripeRows(true);
		
		return gpMasterUser;
	}
	
	// Form Panel
	private FormPanel createFormInput()
	{
		FormPanel panel = new FormPanel();
		panel.setHeaderVisible(false);
		
		FormLayout flLogin = new FormLayout();
		flLogin.setLabelWidth(100);
		
		FieldSet fsLogin = new FieldSet();
		fsLogin.setHeading("Property Login");
		fsLogin.setCollapsible(false);
		fsLogin.setLayout(flLogin);
		
		tfIdUser = new TextField();
		tfIdUser.setId("tfIdUser");
		tfIdUser.setName("tfIdUser");
		tfIdUser.setFieldLabel("ID User");
		tfIdUser.setReadOnly(true);
		tfIdUser.setValue(generateBySystem);
		fsLogin.add(tfIdUser);
		
		tfNamaUser = new TextField();
		tfNamaUser.setId("tfNamaUser");
		tfNamaUser.setName("tfNamaUser");
		tfNamaUser.setFieldLabel("Nama Login");
		fsLogin.add(tfNamaUser);
		
		tfPassword = new TextField();
		tfPassword.setId("tfPassword");
		tfPassword.setName("tfPassword");
		tfPassword.setFieldLabel("Password");
		tfPassword.setPassword(true);
		tfPassword.setMinLength(4);
		fsLogin.add(tfPassword);

		tfPasswordOriginal = new TextField();
		tfPasswordOriginal.setId("tfPasswordOriginal");
		tfPasswordOriginal.setName("tfPasswordOriginal");
		tfPasswordOriginal.setFieldLabel("PasswordOriginal");
		tfPasswordOriginal.setPassword(true);
		tfPasswordOriginal.setMinLength(4);
		tfPasswordOriginal.hide();
		fsLogin.add(tfPasswordOriginal);
		
		FormLayout flWilKerja = new FormLayout();
		flWilKerja.setLabelWidth(100);
		
		FieldSet fsWilKerja = new FieldSet();
		fsWilKerja.setHeading("Wilayah Kerja");
		fsWilKerja.setCollapsible(false);
		fsWilKerja.setLayout(flWilKerja);
	    
		cbUnit = new ComboBox();
		cbUnit.setId("cbUnit");
		cbUnit.setFieldLabel("Unit");
		cbUnit.setDisplayField("nama_unit");
		cbUnit.setValueField("id_singkat");
		cbUnit.setTriggerAction(TriggerAction.ALL);
	    cbUnit.setStore(storeCbUnit);
	    cbUnit.setEmptyText("Select Unit...");  
	    cbUnit.setTypeAhead(false);
	    cbUnit.setEditable(false);
	    fsWilKerja.add(cbUnit);
		
		cbLevelUser = new ComboBox();
		cbLevelUser.setId("cbLevelUser");
		cbLevelUser.setFieldLabel("Level User");
		cbLevelUser.setDisplayField("keterangan");
		cbLevelUser.setValueField("id_level");
		cbLevelUser.setTriggerAction(TriggerAction.ALL);
		cbLevelUser.setStore(storeCbLevelUser);
		cbLevelUser.setEmptyText("Select Level User..."); 
		cbLevelUser.setTypeAhead(false);
		cbLevelUser.setEditable(false);
	    fsWilKerja.add(cbLevelUser);
	    
	    
		FormLayout flInfoAdmin = new FormLayout();
		flInfoAdmin.setLabelWidth(100);
		
		FieldSet fsInfoAdmin = new FieldSet();
		fsInfoAdmin.setHeading("Informasi User");
		fsInfoAdmin.setCollapsible(false);
		fsInfoAdmin.setLayout(flInfoAdmin);

		tfNamaPanjang = new TextField();
		tfNamaPanjang.setId("tfNamaPanjang");
		tfNamaPanjang.setName("tfNamaPanjang");
		tfNamaPanjang.setFieldLabel("Nama Lengkap");
		fsInfoAdmin.add(tfNamaPanjang);

		tfNoNip = new TextField();
		tfNoNip.setId("tfNoNip");
		tfNoNip.setName("tfNoNip");
		tfNoNip.setFieldLabel("NIP");
		fsInfoAdmin.add(tfNoNip);

		tfAlamat = new TextField();
		tfAlamat.setId("tfAlamat");
		tfAlamat.setName("tfAlamat");
		tfAlamat.setFieldLabel("Alamat");
		fsInfoAdmin.add(tfAlamat);

		tfTelp = new TextField();
		tfTelp.setId("tfTelp");
		tfTelp.setName("tfTelp");
		tfTelp.setFieldLabel("Nomor Telp");
		fsInfoAdmin.add(tfTelp);

		tfEmail = new TextField();
		tfEmail.setId("tfEmail");
		tfEmail.setName("tfEmail");
		tfEmail.setFieldLabel("Email");
		fsInfoAdmin.add(tfEmail);
		

		panel.add(fsLogin);
		panel.add(fsWilKerja);
		panel.add(fsInfoAdmin);

	    ContentPanel p = new ContentPanel();
	    p.setHeaderVisible(false);	    
	    p.setButtonAlign(HorizontalAlignment.RIGHT);

	    bSubmit.addListener(Events.OnClick, new SelectionListener<ButtonEvent>() {
			public void handleEvent(ButtonEvent be)
			{
				try
				{	
					if (!tfIdUser.getRawValue().toString().equalsIgnoreCase(generateBySystem))
					{
						if (!tfPassword.getRawValue().toString().equalsIgnoreCase(tfPasswordOriginal.getRawValue().toString()))
						{
							throw new Exception("Update Password tidak dapat dilakukan disini.");
						} else
						{
							//update	
				    	  	mapParam = new FastMap();
				    		mapParam.put("idUser", tfIdUser.getRawValue());	
				    		mapParam.put("namaLogin", tfNamaUser.getRawValue());	
				    		mapParam.put("Password", tfPassword.getRawValue());	
				    		mapParam.put("PasswordOriginal", tfPasswordOriginal.getRawValue());	
				    		mapParam.put("unit", cbUnit.getValue().get("id_singkat"));	
				    		mapParam.put("levelUser", cbLevelUser.getValue().get("id_level"));	
				    		mapParam.put("namaLengkap", tfNamaPanjang.getRawValue());	
				    		mapParam.put("nip", tfNoNip.getRawValue());	
				    		mapParam.put("alamat", tfAlamat.getRawValue());	
				    		mapParam.put("nomorTelp", tfTelp.getRawValue());
				    		mapParam.put("email", tfEmail.getRawValue());	   
				    		
							secmanService.manageMasterUser("UPDATE", mapParam, new AsyncCallback<List<Map>>() {
								public void onFailure(Throwable caught) {
									GWT.log(caught.getMessage(), null);
								}

								public void onSuccess(List<Map> result) {
									String gethasil = result.get(0).get("gethasil").toString();
									
									if (gethasil.equalsIgnoreCase("TRUE"))
									{
										initGridStore();
										MessageBox.info("Update", "Berhasil Update", null);
									}
									else
									{
										MessageBox.alert("Update", "Gagal Update: " + gethasil, null);
									}
								}
							});
						}
					} else
					{
						//insert baru
			    	  	mapParam = new FastMap();
			    		mapParam.put("idUser", tfIdUser.getRawValue());	
			    		mapParam.put("namaLogin", tfNamaUser.getRawValue());	
			    		mapParam.put("Password", tfPassword.getRawValue());		
			    		mapParam.put("unit", cbUnit.getValue().get("id_singkat"));	
			    		mapParam.put("levelUser", cbLevelUser.getValue().get("id_level"));	
			    		mapParam.put("namaLengkap", tfNamaPanjang.getRawValue());	
			    		mapParam.put("nip", tfNoNip.getRawValue());	
			    		mapParam.put("alamat", tfAlamat.getRawValue());	
			    		mapParam.put("nomorTelp", tfTelp.getRawValue());
			    		mapParam.put("email", tfEmail.getRawValue());	   
			    		
						secmanService.manageMasterUser("INSERT", mapParam, new AsyncCallback<List<Map>>() {
							public void onFailure(Throwable caught) {
								GWT.log(caught.getMessage(), null);
							}

							public void onSuccess(List<Map> result) {
								String gethasil = result.get(0).get("gethasil").toString();
								
								if (gethasil.equalsIgnoreCase("TRUE"))
								{
									initGridStore();
									MessageBox.info("Tambah User", "Berhasil Menambah User", null);
								}
								else
								{
									MessageBox.alert("Tambah User", "Gagal Tambah User: " + gethasil, null);
								}
							}
						});
					}
				}
				catch(Exception ex)
				{
					MessageBox.alert("Kesalahan", ex.getMessage().toString(), null);
				}
			}

			@Override
			public void componentSelected(ButtonEvent ce) {}
		});
	    
	    bDelete.disable();
	    bDelete.addListener(Events.OnClick, new SelectionListener<ButtonEvent>() {
			public void handleEvent(ButtonEvent be)
			{
				MessageBox box = new MessageBox();  
		        box.setButtons(MessageBox.YESNO);  
		        box.setIcon(MessageBox.QUESTION);  
		        box.setTitle("Delete User");  
		        box.addCallback(l);  
		        box.setMessage("Delete user: " + tfNamaUser.getValue() + " ?");  
		        box.show();  
			}

			@Override
			public void componentSelected(ButtonEvent ce) {}
		});
	    
	    
	    Button bReset = new Button("Reset",new SelectionListener<ButtonEvent>() {
			@Override
			public void componentSelected(ButtonEvent ce) {
				tfIdUser.setValue(generateBySystem);
				tfNamaUser.clear();
				tfPassword.clear();
				tfNoNip.clear();
				tfAlamat.clear();
				tfTelp.clear();
				tfEmail.clear();
				tfNamaPanjang.clear();
				
				tfPasswordOriginal.clear();

				bDelete.disable();
				
				Info.display("Informasi", "Reset form input..");
			}
		});

	    p.addButton(bSubmit);
	    p.addButton(bDelete);
	    p.addButton(bReset);

	    panel.add(p);
		return panel;
	}
	
	// listener
    final Listener<MessageBoxEvent> l = new Listener<MessageBoxEvent>() {  
		public void handleEvent(MessageBoxEvent ce) {  
		    if(ce.getButtonClicked().getText().equalsIgnoreCase("Yes"))
		    {

	    	  	mapParam = new FastMap();
	    		mapParam.put("idUser", tfIdUser.getRawValue());	
	    		
				secmanService.manageMasterUser("DELETE", mapParam, new AsyncCallback<List<Map>>() {
					public void onFailure(Throwable caught) {
						GWT.log(caught.getMessage(), null);
					}

					public void onSuccess(List<Map> result) {
						String gethasil = result.get(0).get("gethasil").toString();
						
						if (gethasil.equalsIgnoreCase("TRUE"))
						{
							initGridStore();
							MessageBox.info("Hapus User", "User dihapus", null);
						}
						else
						{
							MessageBox.alert("Hapus User", "Gagal Hapus User: " + gethasil, null);
						}
					}
				});
		    } else
		    {
		    	MessageBox.alert("Delete User", "Batal Hapus User", null);
		    }
		}  
    }; 
}
